import re

from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import reqparse
from util.myjwt import myjwt
from util.captcha.captcha import captcha
import json, random, time, requests
from util.myredis import r
from util.smssdk import send_message
from models.user import *
from util.comm import get_ali_object


pay_blue = Blueprint("pay",__name__)

@pay_blue.route('/payurl')
def pagurl():
    userid = request.args.get('userid')
    money = request.args.get('money')

    number = str(int(time.time()))+str(userid)+str(random.randint(10000,99999))
    ref = refil(number=number,money=money,status=0,userid=userid)
    db.session.add(ref)
    db.session.commit()
    pay_time= int(time.time())+30
    r.sortedset_add('refil',number,pay_time)
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject=str(userid) + "充值记录",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })

@pay_blue.route('/callback')
def callback():
    data = request.args
    print(data)
    # 对参数进行处理
    datames = {k: v for k, v in data.items()}
    # 从字典中将sign删除
    # sign = datames.pop("sign")
    sign = datames.pop("sign")
    # 获取支付宝对象
    alipay = get_ali_object()
    # 调用验签
    flag = alipay.verify(datames, sign)
    print(flag)
    if flag == True:
        trade_no = datames['trade_no']
        out_trade_no = datames['out_trade_no']  # 订单号
        ref = refil.query.filter_by(number=out_trade_no).first()
        userid = ref.userid
        print('userid',userid)
        money = ref.money
        print('money',money)
        users = User.query.filter_by(id=userid).first()
        umoney = users.money
        print('umoney',umoney)
        tmoney = money+umoney #当前用户总金额
        print('tmoney',tmoney)
        try:
            User.query.filter_by(id=userid).update({'money':tmoney})
            print(333)
            refil.query.filter_by(number=out_trade_no).update({'status':1,'serialnumber':trade_no})
            print(444)
            refils = refil_change(money=money,descs=1,userid=userid)
            db.session.add(refils)
            print(555)
            db.session.commit()
        except:
            return jsonify({'code': 1002, 'msg': '禁止盲目个别更改'})

        return redirect("http://localhost:8080/pay")
    return jsonify({'code': 1002, 'msg': '验签失败'})

def payment():
    data = datetime.datetime.now()-datetime.timedelta(minutes=1)
    now = datetime.datetime.strftime(data,'%Y-%m-%d 00:59:59')
    refils=refil.query.filter_by(status=0).all()
    # print(refils.create_time)
    for i in refils:
        print(i.create_time)

        pay = get_ali_object()
        print(pay)

        query_params = pay.query_pay(
            out_trade_no=i.number
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        res = requests.get(pay_url)
        print(res.text)
        aa = json.loads(res.text)
        code = aa["alipay_trade_query_response"]['code']
        print(code)
        if int(code) == 40004:
            print(1)
            # if str(i.create_time) < str(now):
            refil.query.filter_by(number=i.number).delete()

            db.session.commit()
            print('>>>>>>>>')
            return '交易失效'
        if int(code) == 10000:
            print(2)
            return 'ok'
            # sql = "delete from payrecord where number='%s'"%(i.decode())
            # r.sortedset_delete("numberpay", i.decode())
    else:
        return "没有数据"




@pay_blue.route('/getusermoney')
def getusermoney():
    userid = request.args.get('userid')
    user = User.query.filter_by(id=userid).first()
    money = user.money
    lockmoney = user.lockmoney
    return jsonify({'code':200,'money':money,'lockmoney':lockmoney})






# @pay_blue.route('/user/callback/')
# def call():
#     # 接收参数
#     data = request.args
#     datames = {k:v for k,v in data.items()}
#     # 删除字典中key为sign的记录
#     sign = datames.pop('sign')
#     # 鉴权 订单号 流水号
#     pay = get_ali_object()
#     flag = pay.verify(datames,sign)
#     if flag == True:
#         # try:
#         order_no = request.args.get('out_trade_no')
#         print('lllll',order_no)
#         res = VipRecord.query.filter_by(order_no=order_no).first()
#         print(res)
#         uid = int(res.userid)
#         year=res.year
#         ryear=365 * int(year)
#         stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
#         etime = datetime.datetime.now() +datetime.timedelta(days=ryear)
#         etime = datetime.datetime.strftime(etime,"%Y-%m-%d %H:%M:%S")
#         v = Vip.query.filter_by(userid=uid).first()
#         if v is not None:
#             #添加结束时
#             etime1 = v.e_time
#             etime2 = etime1 + datetime.timedelta(days=ryear) #月
#             etime3 = datetime.datetime.strftime(etime2, "%Y-%m-%d %H:%M:%S")
#             v.e_time = etime3
#             db.session.add(v)
#         else:
#             vip = Vip(userid=uid,s_time=stime,e_time=etime)
#             db.session.add(vip)
#
#         order=VipRecord.query.filter_by(order_no=order_no).first()
#         order.status = 2
#         user = User.query.filter_by(id=uid).first()
#         user.level = 2
#         # User.query.filter_by(userid=uid).update(level=2)
#         db.session.commit()
#         # except:
#         #     db.session.rollback()
#     return redirect("http://localhost:8080/#/vip")
